package cn.hg.solon.youcan.easyquery.util;

import cn.hg.solon.youcan.easyquery.core.sql.PropertySort;
import com.easy.query.api.proxy.entity.select.EntityQueryable;
import com.easy.query.core.proxy.ProxyEntity;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.db.Page;
import org.dromara.hutool.db.sql.Direction;
import org.dromara.hutool.db.sql.Order;

public class EntityQueryableUtil {

    public static <P extends ProxyEntity<P, E>, E> EntityQueryable applyOrderBy(EntityQueryable<P, E> entityQuery, Page page) {
        if (ObjUtil.isNull(page)) {
            return entityQuery;
        }

        Order[] orders = page.getOrders();
        if (ArrayUtil.isNotEmpty(orders)) {
            for (Order o : orders) {
                entityQuery.orderByObject(new PropertySort(o.getField(), ObjUtil.equals(o.getDirection(), Direction.ASC)));
            }
        }

        return entityQuery;
    }

    public static <P extends ProxyEntity<P, E>, E> EntityQueryable applyOrderBy(EntityQueryable<P, E> entityQuery, Order order) {
        if (ObjUtil.isNull(order)) {
            return entityQuery;
        }
        return entityQuery.orderByObject(new PropertySort(order.getField(), ObjUtil.equals(order.getDirection(), Direction.ASC)));
    }
}
